package com.example.sendsms;

import static android.os.Environment.DIRECTORY_DOWNLOADS;

import android.Manifest;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.sendsms.utils.PermissionUtil;

import java.io.File;

public class MainActivity extends AppCompatActivity {


    private Uri pictureUri;
    private GridLayout pictures;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        ImageView imageBox = findViewById(R.id.imageBox);

        ActivityResultLauncher<Intent> selectPicture = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), res -> {
            if (res.getResultCode() != RESULT_OK) {
                return;
            }
            Intent data = res.getData();
            if (data == null) {
                return;
            }
            pictureUri = data.getData();
            imageBox.setImageURI(pictureUri);
        });


        imageBox.setOnClickListener(view -> {
            // 跳转系统相册，选择图片
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            // 设置内容为图片类型
            intent.setType("image/*");
            selectPicture.launch(intent);
        });

        findViewById(R.id.sendSms).setOnClickListener(view -> {

            if (pictureUri == null) {

                Toast.makeText(this, "请选择图片", Toast.LENGTH_SHORT).show();
                return;
            }

            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.putExtra("address", "13211634008");
            intent.putExtra("subject", "这是一封彩信");
            intent.putExtra("sms_body", "彩信内容");
            intent.putExtra(Intent.EXTRA_STREAM, pictureUri);

            intent.setType("image/*");
// 允许接收者读取 Uri中的数据
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);

            startActivity(intent);
        });

        pictures = findViewById(R.id.pictures);

        // 手动把 图片信息扫描进 MediaStore
        File download = Environment.getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS);
        MediaScannerConnection.scanFile(this, new String[]{download.getAbsolutePath()}, null, (path, uri) -> {
            // 扫描更新完成数据库再加载图片
            // 不行，因为这里不是主线程，非主线程不能操作UI
        });
        loadPictures();

    }

    private void loadPictures() {
        if (PermissionUtil.requestPermission(this, 2, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE})) {

            doLoadPictures();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 2) {
            doLoadPictures();
        }
    }

    private void doLoadPictures() {

        int widthPixels = getResources().getDisplayMetrics().widthPixels;

        try (Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{
                        MediaStore.Images.Media._ID,
                        MediaStore.Images.Media.TITLE,
                        MediaStore.Images.Media.SIZE,
                        MediaStore.Images.Media.DATA
                },
                null,//"_size > 3072",
                null, null
        )) {
            if (cursor == null) {
                return;
            }
            int index = 0;

            while (cursor.moveToNext() && index < 6) {


                ImageView imageView = new ImageView(this);
                imageView.setImageURI(Uri.parse(cursor.getString(3)));


                imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);

                // 创建GridLayout.LayoutParams并设置对齐方式、间距等
                GridLayout.Spec rowSpec = GridLayout.spec(index , 1f);
                GridLayout.Spec columnSpec = GridLayout.spec(0  , 1f);

                // imageView.setScaleX(0.2f);
                // imageView.setScaleY(0.2f);
                //imageView.setLayoutParams(new ViewGroup.LayoutParams(110,110));
                GridLayout.LayoutParams params = new GridLayout.LayoutParams(rowSpec, columnSpec);
                params.width = GridLayout.LayoutParams.WRAP_CONTENT;
                params.height = GridLayout.LayoutParams.WRAP_CONTENT;
                pictures.addView(imageView, params);
                index++;


            }
            pictures.setRowCount(index);
        }
    }
}